<template>
	<view>
		<view class="uni-header">
			<view class="uni-group">
				<view class="uni-title">商户提现申请管理</view>
				<view class="uni-sub-title">审核并处理商户提现申请</view>
			</view>
			<view class="uni-group">
				<input class="uni-search" type="text" v-model="query" @confirm="search" placeholder="请输入商户ID或申请人ID" />
				<button class="uni-button" type="default" size="mini" @click="search">搜索</button>
				<button class="uni-button" type="default" size="mini" :disabled="!selectedIndexs.length"
					@click="delTable">批量删除</button>
				<download-excel class="hide-on-phone" :fields="exportExcel.fields" :data="exportExcelData"
					:type="exportExcel.type" :name="exportExcel.filename">
					<button class="uni-button" type="primary" size="mini">导出 Excel</button>
				</download-excel>
			</view>
		</view>
		<view class="uni-container">
			<unicloud-db ref="udb" :collection="collectionList"
				field="_id,merchant_id,applyuser_id,amount,fee,actual_amount,withdraw_type,available_balance,frozen_balance,remark,reason,status,account_info,audit_info,payment_info,create_date"
				:where="where" page-data="replace" :orderby="orderby" :getcount="true" :page-size="options.pageSize"
				:page-current="options.pageCurrent" v-slot:default="{data,pagination,loading,error,options}"
				:options="options" loadtime="manual" @load="onqueryload">
				<uni-table ref="table" :loading="loading" :emptyText="error.message || '没有更多数据'" border stripe
					type="selection" @selection-change="selectionChange">
					<uni-tr>
						<uni-th align="center" sortable
							@sort-change="sortChange($event, 'merchant_id')">商户ID</uni-th>
						<uni-th align="center" sortable
							@sort-change="sortChange($event, 'applyuser_id')">申请人ID</uni-th>
						<uni-th align="center" sortable @sort-change="sortChange($event, 'amount')">提现金额</uni-th>
						<uni-th align="center" sortable @sort-change="sortChange($event, 'fee')">手续费</uni-th>
						<uni-th align="center" sortable
							@sort-change="sortChange($event, 'actual_amount')">实际到账</uni-th>
						<uni-th align="center" filter-type="select"
							:filter-data="options.filterData.withdraw_type_localdata"
							@filter-change="filterChange($event, 'withdraw_type')">提现方式</uni-th>
						<uni-th align="center">支付宝账户</uni-th>
						<uni-th align="center" filter-type="search" @filter-change="filterChange($event, 'remark')"
							>备注</uni-th>
						<uni-th align="center" filter-type="select" :filter-data="options.filterData.status_localdata"
							@filter-change="filterChange($event, 'status')">状态</uni-th>
						<uni-th align="center">审核信息</uni-th>
						<uni-th align="center" filter-type="timestamp"
							@filter-change="filterChange($event, 'create_date')" sortable
							@sort-change="sortChange($event, 'create_date')">申请时间</uni-th>
						<uni-th align="center" width="200">操作</uni-th>
					</uni-tr>
					<uni-tr v-for="(item,index) in data" :key="index">
						<uni-td align="center">{{item.merchant_id}}</uni-td>
						<uni-td align="center">{{item.applyuser_id}}</uni-td>
						<uni-td align="center">¥{{item.amount}}</uni-td>
						<uni-td align="center">¥{{item.fee}}</uni-td>
						<uni-td align="center">¥{{item.actual_amount}}</uni-td>
						<uni-td align="center">{{options.withdraw_type_valuetotext[item.withdraw_type]}}</uni-td>
						<uni-td align="left">
							<view v-if="item.account_info">
								<view>姓名：{{item.account_info.name}}</view>
								<view>账号：{{item.account_info.account}}</view>
								<view>手机：{{item.account_info.phone}}</view>
							</view>
						</uni-td>
						<uni-td align="center">{{item.remark || '-'}}</uni-td>
						<uni-td align="center">
							<uni-tag :text="options.status_valuetotext[item.status]" 
								:type="getStatusType(item.status)"></uni-tag>
						</uni-td>
						<uni-td align="left">
							<view v-if="item.audit_info && item.audit_info.audit_time">
								<view>审核人：{{item.audit_info.auditor_id}}</view>
								<view>审核时间：<uni-dateformat :date="item.audit_info.audit_time"></uni-dateformat></view>
								<view v-if="item.audit_info.audit_remark">备注：{{item.audit_info.audit_remark}}</view>
							</view>
							<view v-else>-</view>
						</uni-td>
						<uni-td align="center">
							<uni-dateformat :threshold="[0, 0]" :date="item.create_date"></uni-dateformat>
						</uni-td>
						<uni-td align="center">
							<view class="uni-group">
<!-- 								<button @click="queryAlipayAccount"
									class="uni-button" size="mini" type="primary">测试</button> -->
								<!-- 状态0：审核中，显示审核按钮 -->
								<button v-if="item.status === 0" @click="showAuditDialog(item)" 
									class="uni-button" size="mini" type="primary">审核</button>
								<!-- 状态1：已通过，显示打款按钮 -->
								<button v-else-if="item.status === 1" @click="showPaymentDialog(item)" 
									class="uni-button" size="mini" type="success">打款</button>
								<!-- 状态2：已拒绝，显示拒绝原因 -->
								<button v-else-if="item.status === 2" @click="showRejectReason(item)" 
									class="uni-button" size="mini" type="default">查看原因</button>
								<!-- 状态3：打款成功，显示打款信息 -->
								<button v-else-if="item.status === 3" @click="showPaymentInfo(item)" 
									class="uni-button" size="mini" type="default">查看打款</button>
								<!-- 状态4：打款失败，显示重新打款 -->
								<button v-else-if="item.status === 4" @click="showPaymentDialog(item)" 
									class="uni-button" size="mini" type="warn">重新打款</button>
								<!-- 只能删除审核中或已拒绝的记录 -->
								<button v-if="item.status === 0 || item.status === 2" 
									@click="confirmDelete(item._id)" class="uni-button" size="mini"
									type="warn">删除</button>
							</view>
						</uni-td>
					</uni-tr>
				</uni-table>
				<view class="uni-pagination-box">
					<uni-pagination show-icon :page-size="pagination.size" v-model="pagination.current"
						:total="pagination.count" @change="onPageChanged" />
				</view>
			</unicloud-db>
		</view>
		
		<!-- 审核弹窗 -->
		<uni-popup ref="auditPopup" type="dialog">
			<uni-popup-dialog mode="input" title="审核提现申请" 
				:value="auditForm.audit_remark" 
				placeholder="请输入审核备注（选填）"
				@confirm="handleAuditConfirm" 
				@close="closeAuditDialog">
				<view class="audit-content">
					<view class="audit-info">
						<view class="info-row">
							<text class="label">商户ID：</text>
							<text>{{currentItem.merchant_id}}</text>
						</view>
						<view class="info-row">
							<text class="label">提现金额：</text>
							<text class="amount">¥{{currentItem.amount}}</text>
						</view>
						<view class="info-row">
							<text class="label">手续费：</text>
							<text>¥{{currentItem.fee}}</text>
						</view>
						<view class="info-row">
							<text class="label">实际到账：</text>
							<text class="amount-highlight">¥{{currentItem.actual_amount}}</text>
						</view>
						<view class="info-row">
							<text class="label">支付宝姓名：</text>
							<text>{{currentItem.account_info?.name}}</text>
						</view>
						<view class="info-row">
							<text class="label">支付宝账号：</text>
							<text>{{currentItem.account_info?.account}}</text>
						</view>
						<view class="info-row">
							<text class="label">身份证号：</text>
							<text>{{currentItem.account_info?.id_card_no}}</text>
						</view>
						<view class="info-row">
							<text class="label">手机号：</text>
							<text>{{currentItem.account_info?.phone}}</text>
						</view>
					</view>
					<view class="audit-actions">
						<button @click="auditPass" class="uni-button" type="primary">通过</button>
						<button @click="showRejectInput" class="uni-button" type="warn">拒绝</button>
					</view>
					<!-- 拒绝原因输入 -->
					<view v-if="showRejectReasonInput" class="reject-reason">
						<textarea v-model="auditForm.reason" placeholder="请输入拒绝原因（必填）" 
							class="reject-textarea" maxlength="200"></textarea>
						<button @click="auditReject" class="uni-button" type="warn" 
							:disabled="!auditForm.reason">确认拒绝</button>
					</view>
				</view>
			</uni-popup-dialog>
		</uni-popup>
		
		<!-- 打款弹窗 -->
		<uni-popup ref="paymentPopup" type="dialog">
			<uni-popup-dialog title="确认打款" 
				class="payment-dialog"
				@close="closePaymentDialog">
				<view class="payment-content">
					<view class="payment-info">
						<view class="info-row">
							<text class="label">商户ID：</text>
							<text>{{currentItem.merchant_id}}</text>
						</view>
						<view class="info-row">
							<text class="label">提现金额：</text>
							<text class="amount-highlight">¥{{currentItem.actual_amount}}</text>
						</view>
						<view class="info-row">
							<text class="label">收款人：</text>
							<text>{{currentItem.account_info?.name}}</text>
						</view>
						<view class="info-row">
							<text class="label">支付宝账号：</text>
							<text>{{currentItem.account_info?.account}}</text>
						</view>
						<view class="warning-text">
							<text>⚠️ 请仔细核对打款信息，确认后将通过支付宝转账到上述账户</text>
						</view>
					</view>
					<!-- 备注输入（选填） -->
					<view class="reject-reason">
						<textarea v-model="paymentForm.payment_remark" 
							class="reject-textarea" 
							placeholder="请输入打款备注（选填）" 
							maxlength="200"></textarea>
					</view>
					<view class="payment-actions">
						<button @click="closePaymentDialog" class="uni-button" type="default" 
							:disabled="paymentLoading">取消</button>
						<button @click="confirmPayment" class="uni-button" type="primary" 
							:loading="paymentLoading" :disabled="paymentLoading">
							{{paymentLoading ? '处理中...' : '确认打款'}}
						</button>
					</view>
				</view>
			</uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script>
	import {
		enumConverter,
		filterToWhere
	} from '../../js_sdk/validator/intangible_withdrawalapply.js';

	const db = uniCloud.database()
	// 表查询配置
	const dbOrderBy = '' // 排序字段
	const dbSearchFields = [] // 模糊搜索字段，支持模糊搜索的字段列表。联表查询格式: 主表字段名.副表字段名，例如用户表关联角色表 role.role_name
	// 分页配置
	const pageSize = 20
	const pageCurrent = 1

	const orderByMapping = {
		"ascending": "asc",
		"descending": "desc"
	}

	export default {
		data() {
			return {
				collectionList: "intangible_withdrawalapply",
				query: '',
				where: '',
				orderby: dbOrderBy,
				orderByFieldName: "",
				selectedIndexs: [],
				options: {
					pageSize,
					pageCurrent,
					filterData: {
						"withdraw_type_localdata": [{
							"text": "支付宝",
							"value": 0
						}],
						"status_localdata": [{
								"text": "审核中",
								"value": 0
							},
							{
								"text": "已通过,待打款",
								"value": 1
							},
							{
								"text": "已拒绝",
								"value": 2
							},
							{
								"text": "打款成功",
								"value": 3
							},
							{
								"text": "打款失败",
								"value": 4
							}
						]
					},
					...enumConverter
				},
				imageStyles: {
					width: 64,
					height: 64
				},
				exportExcel: {
					"filename": "intangible_withdrawalapply.xls",
					"type": "xls",
					"fields": {
						"商户ID": "merchant_id",
						"申请人ID": "applyuser_id",
						"提现金额": "amount",
						"手续费": "fee",
						"实际到账金额": "actual_amount",
						"提现方式": "withdraw_type",
						"备注": "remark",
						"拒绝原因": "reason",
						"状态": "status",
						"申请时间": "create_date"
					}
				},
				exportExcelData: [],
				// 当前操作的项
				currentItem: {},
				// 审核表单
				auditForm: {
					audit_remark: '',
					reason: ''
				},
				showRejectReasonInput: false,
				// 打款表单
				paymentForm: {
					payment_remark: ''
				},
				paymentLoading: false
			}
		},
		onLoad() {
			this._filter = {}
		},
		onReady() {
			this.$refs.udb.loadData()
		},
		methods: {
			async queryAlipayAccount(){
				const mwithdrawobj = uniCloud.importObject('merchant-withdraw')
				const res = await mwithdrawobj.queryAlipayAccount()
				console.log(222222222222222,res)
			},
			// 获取状态标签类型
			getStatusType(status) {
				const typeMap = {
					0: 'warning',  // 审核中
					1: 'primary',  // 已通过
					2: 'error',    // 已拒绝
					3: 'success',  // 打款成功
					4: 'error'     // 打款失败
				}
				return typeMap[status] || 'default'
			},
			
			// 显示审核弹窗
			showAuditDialog(item) {
				this.currentItem = item
				this.auditForm = {
					audit_remark: '',
					reason: ''
				}
				this.showRejectReasonInput = false
				this.$refs.auditPopup.open()
			},
			
			// 关闭审核弹窗
			closeAuditDialog() {
				this.$refs.auditPopup.close()
				this.currentItem = {}
				this.showRejectReasonInput = false
			},
			
			// 显示拒绝原因输入框
			showRejectInput() {
				this.showRejectReasonInput = true
			},
			
			// 审核通过
			async auditPass() {
				const {uid} = uniCloud.getCurrentUserInfo()
				uni.showLoading({ title: '处理中...' })
				try {
					const updateData = {
						status: 1, // 已通过，待打款
						audit_info: {
							auditor_id: uid || '', // 当前管理员ID
							audit_time: Date.now(),
							audit_remark: this.auditForm.audit_remark || '审核通过'
						}
					}
					
					await db.collection('intangible_withdrawalapply')
						.doc(this.currentItem._id)
						.update(updateData)
					
					uni.hideLoading()
					uni.showToast({
						title: '审核通过',
						icon: 'success'
					})
					this.closeAuditDialog()
					this.loadData(false)
				} catch (error) {
					uni.hideLoading()
					uni.showToast({
						title: '操作失败：' + error.message,
						icon: 'none'
					})
				}
			},
			
			// 审核拒绝
			async auditReject() {
				if (!this.auditForm.reason || !this.auditForm.reason.trim()) {
					uni.showToast({
						title: '请输入拒绝原因',
						icon: 'none'
					})
					return
				}
				
				uni.showLoading({ title: '处理中...' })
				try {
					const updateData = {
						status: 2, // 已拒绝
						reason: this.auditForm.reason.trim(),
						audit_info: {
							auditor_id: this.$store.state.user.userInfo._id || '', // 当前管理员ID
							audit_time: Date.now(),
							audit_remark: this.auditForm.audit_remark || '审核不通过'
						}
					}
					
					await db.collection('intangible_withdrawalapply')
						.doc(this.currentItem._id)
						.update(updateData)
					
					uni.hideLoading()
					uni.showToast({
						title: '已拒绝申请',
						icon: 'success'
					})
					this.closeAuditDialog()
					this.loadData(false)
				} catch (error) {
					uni.hideLoading()
					uni.showToast({
						title: '操作失败：' + error.message,
						icon: 'none'
					})
				}
			},
			
			// 显示拒绝原因
			showRejectReason(item) {
				uni.showModal({
					title: '拒绝原因',
					content: item.reason || '无',
					showCancel: false
				})
			},
			
			// 显示打款弹窗
			showPaymentDialog(item) {
				this.currentItem = item
				this.paymentForm = {
					payment_remark: ''
				}
				this.$refs.paymentPopup.open()
			},
			
			// 关闭打款弹窗
			closePaymentDialog() {
				this.$refs.paymentPopup.close()
				this.currentItem = {}
			},
			
			// 确认打款
			async confirmPayment() {
				const {uid} = uniCloud.getCurrentUserInfo()
				this.paymentLoading = true
				
				try {
					// 调用云对象进行支付宝转账
					const mwithdrawobj = uniCloud.importObject('merchant-withdraw')
					
					// 构建转账参数
					const transferParams = {
						out_biz_no: this.currentItem._id, // 使用提现订单ID作为商家订单号
						trans_amount: this.currentItem.actual_amount, // 实际到账金额
						order_title: `商户提现-${this.currentItem.merchant_id}`,
						biz_scene: 'DIRECT_TRANSFER',
						product_code: 'TRANS_ACCOUNT_NO_PWD',
						payee_info: {
							identity: this.currentItem.account_info.account, // 支付宝账号
							identity_type: 'ALIPAY_LOGON_ID' ,// 登录号类型
							name:this.currentItem.account_info.name
						}
					}
					
					const transferResult = await mwithdrawobj.uniTransfer(transferParams)
					// console.log(9999999999999,transferResult)
					
					if (transferResult.success) {
						// 打款成功，更新数据库
						const paymentData = transferResult.result.data
						const updateData = {
							status: 3, // 打款成功
							payment_info: {
								operator_id: uid || '', // 操作人ID
								trans_date: Date.now(),
								payment_method: '支付宝转账',
								order_id: paymentData.order_id || '',
								pay_fund_order_id: paymentData.pay_fund_order_id || '',
								payment_remark: this.paymentForm.payment_remark || '打款成功'
							}
						}
						
						await db.collection('intangible_withdrawalapply')
							.doc(this.currentItem._id)
							.update(updateData)
						
						uni.showToast({
							title: '打款成功',
							icon: 'success'
						})
						this.closePaymentDialog()
						this.loadData(false)
					} else {
						// 打款失败，更新状态
						const updateData = {
							status: 4, // 打款失败
							payment_info: {
								operator_id: uid || '',
								trans_date: Date.now(),
								payment_method: '支付宝转账',
								payment_remark: `打款失败：${transferResult.errMsg || '未知错误'}`
							}
						}
						
						await db.collection('intangible_withdrawalapply')
							.doc(this.currentItem._id)
							.update(updateData)
						
						uni.showModal({
							title: '打款失败',
							content: transferResult.subMsg || transferResult.errMsg || '未知错误',
							showCancel: false
						})
						this.closePaymentDialog()
						this.loadData(false)
					}
				} catch (error) {
					console.error('打款异常:', error)
					uni.showToast({
						title: '打款异常：' + error.message,
						icon: 'none',
						duration: 3000
					})
				} finally {
					this.paymentLoading = false
				}
			},
			
			// 查看打款信息
			showPaymentInfo(item) {
				let content = ''
				if (item.payment_info) {
					content = `打款时间：${item.payment_info.trans_date ? new Date(item.payment_info.trans_date).toLocaleString() : '-'}\n`
					content += `打款方式：${item.payment_info.payment_method || '-'}\n`
					content += `订单号：${item.payment_info.order_id || '-'}\n`
					content += `支付流水号：${item.payment_info.pay_fund_order_id || '-'}\n`
					content += `备注：${item.payment_info.payment_remark || '-'}`
				} else {
					content = '暂无打款信息'
				}
				
				uni.showModal({
					title: '打款信息',
					content: content,
					showCancel: false
				})
			},
			
			handleAuditConfirm(value) {
				this.auditForm.audit_remark = value
			},
			
			onqueryload(data) {
				this.exportExcelData = data
			},
			getWhere() {
				const query = this.query.trim()
				if (!query) {
					return ''
				}
				const queryRe = new RegExp(query, 'i')
				return dbSearchFields.map(name => queryRe + '.test(' + name + ')').join(' || ')
			},
			search() {
				const newWhere = this.getWhere()
				this.where = newWhere
				this.$nextTick(() => {
					this.loadData()
				})
			},
			loadData(clear = true) {
				this.$refs.udb.loadData({
					clear
				})
			},
			onPageChanged(e) {
				this.selectedIndexs.length = 0
				this.$refs.table.clearSelection()
				this.$refs.udb.loadData({
					current: e.current
				})
			},
			navigateTo(url, clear) {
				// clear 表示刷新列表时是否清除页码，true 表示刷新并回到列表第 1 页，默认为 true
				uni.navigateTo({
					url,
					events: {
						refreshData: () => {
							this.loadData(clear)
						}
					}
				})
			},
			// 多选处理
			selectedItems() {
				var dataList = this.$refs.udb.dataList
				return this.selectedIndexs.map(i => dataList[i]._id)
			},
			// 批量删除
			delTable() {
				this.$refs.udb.remove(this.selectedItems(), {
					success: (res) => {
						this.$refs.table.clearSelection()
					}
				})
			},
			// 多选
			selectionChange(e) {
				this.selectedIndexs = e.detail.index
			},
			confirmDelete(id) {
				this.$refs.udb.remove(id, {
					success: (res) => {
						this.$refs.table.clearSelection()
					}
				})
			},
			sortChange(e, name) {
				this.orderByFieldName = name;
				if (e.order) {
					this.orderby = name + ' ' + orderByMapping[e.order]
				} else {
					this.orderby = ''
				}
				this.$refs.table.clearSelection()
				this.$nextTick(() => {
					this.$refs.udb.loadData()
				})
			},
			filterChange(e, name) {
				this._filter[name] = {
					type: e.filterType,
					value: e.filter
				}
				let newWhere = filterToWhere(this._filter, db.command)
				if (Object.keys(newWhere).length) {
					this.where = newWhere
				} else {
					this.where = ''
				}
				this.$nextTick(() => {
					this.$refs.udb.loadData()
				})
			}
		}
	}
</script>

<style scoped>
	/* 隐藏打款弹窗的内置确定/取消按钮，仅作用于该对话框 */
	.payment-dialog >>> .uni-dialog-button-group,
	.payment-dialog /deep/ .uni-dialog-button-group {
		display: none !important;
	}

	.audit-content,
	.payment-content {
		padding: 20rpx;
	}
	
	.audit-info,
	.payment-info {
		margin-bottom: 30rpx;
	}
	
	.info-row {
		display: flex;
		align-items: center;
		margin-bottom: 15rpx;
		font-size: 28rpx;
	}
	
	.label {
		color: #666;
		min-width: 160rpx;
	}
	
	.amount {
		color: #ff5722;
		font-weight: bold;
		font-size: 32rpx;
	}
	
	.amount-highlight {
		color: #ff5722;
		font-weight: bold;
		font-size: 36rpx;
	}
	
	.audit-actions,
	.payment-actions {
		display: flex;
		justify-content: space-around;
		margin-top: 30rpx;
	}
	
	.audit-actions button,
	.payment-actions button {
		flex: 1;
		margin: 0 10rpx;
	}
	
	.reject-reason {
		margin-top: 20rpx;
		padding: 20rpx;
		background-color: #fff3e0;
		border-radius: 8rpx;
	}
	
	.reject-textarea {
		width: 100%;
		min-height: 150rpx;
		padding: 20rpx;
		border: 1px solid #ddd;
		border-radius: 8rpx;
		margin-bottom: 20rpx;
		box-sizing: border-box;
		font-size: 28rpx;
	}
	
	.warning-text {
		margin-top: 20rpx;
		padding: 20rpx;
		background-color: #fff3e0;
		border-left: 4rpx solid #ff9800;
		color: #e65100;
		font-size: 26rpx;
		line-height: 1.5;
	}
</style>